<?php
/**
 * 订单类型枚举模型
 */
declare(strict_types=1);

namespace app\model\crm;

use app\model\BaseModel;

class OrderType extends BaseModel
{
    protected $name = 'crm_order_type';
    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    
    /**
     * 订单大类常量
     */
    const CATEGORY_LAWSUIT = 1;        // 诉讼订单
    const CATEGORY_LEGAL_SERVICE = 2;  // 非诉订单
    
    /**
     * 状态常量
     */
    const STATUS_DISABLED = 0;  // 禁用
    const STATUS_ENABLED = 1;   // 启用
    
    /**
     * 获取订单大类文本
     */
    public function getCategoryTextAttr($value, $data): string
    {
        $categoryMap = [
            self::CATEGORY_LAWSUIT       => '诉讼订单',
            self::CATEGORY_LEGAL_SERVICE => '非诉订单',
        ];
        
        return $categoryMap[$data['category']] ?? '未知';
    }
    
    /**
     * 获取状态文本
     */
    public function getStatusTextAttr($value, $data): string
    {
        $statusMap = [
            self::STATUS_DISABLED => '禁用',
            self::STATUS_ENABLED  => '启用',
        ];
        
        return $statusMap[$data['status']] ?? '未知';
    }
    
    /**
     * 搜索器：订单大类
     */
    public function searchCategoryAttr($query, $value)
    {
        if ($value !== null && $value !== '') {
            $query->where('category', $value);
        }
    }
    
    /**
     * 搜索器：状态
     */
    public function searchStatusAttr($query, $value)
    {
        if ($value !== null && $value !== '') {
            $query->where('status', $value);
        }
    }
    
    /**
     * 获取启用的订单类型列表
     */
    public static function getEnabledTypes(?int $category = null): array
    {
        $query = self::where('status', self::STATUS_ENABLED);
        
        if ($category !== null) {
            $query->where('category', $category);
        }
        
        return $query->order('sort_order', 'asc')
            ->select()
            ->toArray();
    }
}
